/*
又拍云插件--Power by Andiff  weixin:17191079694 QQ:165607361
 */
(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as anonymous module.
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // Node / CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals.
        factory(jQuery);
    }
})(function ($) {
	'use strict';
	//常量
    var UPYUNURL = 'https://v0.api.upyun.com/andiffnet1';   //这里是又拍云请求地址
    //上传接口地址
    var BUCKET = 'andiffnet1';
    //Bucket
    var FORMAPI = 'R1PnbtDDGDw+3xp+RGnsbFVq1RQ=';
    //formapi
    var SAVEPATH = 'ren';
    //保存文件的文件夹
    var URL = '/api/upyunupload/rentoupyun?savepath=';  //这里是控制器请求地址
    var ONLINEURL = 'https://qd.andiff.net/'; //这里换成你的又拍云地址
    var upyun = {
        //类似朋友圈上传多张图片
        uploadPicsByAjax:function(index,ul,dir){
            $.getJSON(URL+dir, function (data) {
                var uploadData = new FormData();
                uploadData.append('file', $('#files'+index)[0].files[0]);
                uploadData.append('policy', data.policy);
                uploadData.append('authorization', data.authorization);
                $.ajax({
                    url: UPYUNURL,
                    type: 'POST',
                    data: uploadData,
                    cache: false,
                    processData: false,
                    contentType: false,
                }).done(function(data, textStatus) {
                    //alert(JSON.stringify(data));
                    var body = jQuery.parseJSON(data);
                    var img = '<img width="100%" src="'+ONLINEURL+body.url+'" />';
                    img = img + '<img class="imgcommon" src="/images/cha.png" />';
                    img = img + '<input type="hidden" name="row[picurl][]" value="'+body.url+'" />';
                    img = img + '<span><input class="form-control" name="row[listorder][]" type="text" value="1" placeholder="顺序" /></span>';
                    $("#"+ul+" li").eq(index).html(img);
                }).fail(function(res, textStatus, error) {
                    try {
                        var body = JSON.parse(res.responseText);
                        alert('error: ' + body.message);
                    } catch(e) {
                        console.error(e);
                    }
                });

            });
        },
        //普通的上传图片文件
        uploadByAjax: function (file1,show1,dir) {
            var filename = '';var fileextname = '';
            if(typeof($('#'+file1)[0].files[0].name)!='undefined'){
                filename = $('#'+file1)[0].files[0].name;
                fileextname = filename.split('.')[1];
            }
            var multiple = $('#'+file1).data('multiple');
            var arry = $('#'+file1).attr("accept").split(',');
            var inarray = $.inArray('.'+fileextname, arry);
            if(inarray==-1){
                alert('请上传'+arry.join()+'文件');
                return;
            }
            $.getJSON(URL+dir+'&ext='+fileextname, function (data) {
                var uploadData = new FormData();
                uploadData.append('file', $('#'+file1)[0].files[0]);
                uploadData.append('policy', data.policy);
                uploadData.append('authorization', data.authorization);
                $.ajax({
                    url: UPYUNURL,
                    type: 'POST',
                    data: uploadData,
                    cache: false,
                    processData: false,
                    contentType: false,
                }).done(function(data, textStatus) {
                    var body = jQuery.parseJSON(data);
                    if(multiple==true){
                        var s = $("#"+show1).val();
                        if(s==''){
                            $("#"+show1).val(body.url);
                        }else{
                            $("#"+show1).val(s+','+body.url);
                        }                        
                    }else{
                        $("#"+show1).val(body.url);
                    }                   
                    if(typeof($('#'+file1).data("preview-id"))!='undefined'){
                        var preid = $('#'+file1).data("preview-id");
                        var str = '';
                        if(multiple==true){
                            //多选
                            str = str + $("#"+preid).html();
                        }                       
                        str = str + '<li class="col-xs-3">';
                        str = str + '<a href="'+ONLINEURL+body.url+'" data-url="'+ONLINEURL+body.url+'" target="_blank" class="thumbnail">';
                        str = str + '<img src="'+ONLINEURL+body.url+'" class="img-responsive" /></a>';
                        str = str + '<a href="javascript:;" class="btn btn-danger btn-xs btn-trash"><i class="fa fa-trash"></i></a>';
                        str = str + '</li>';
                        $("#"+preid).html(str);
                    }
                    $(document).on("click", "#" + preid + " .btn-trash", function () {
                        var url = $(this).prev().attr('href').replace(ONLINEURL,"");                        
                        var arry = $("#"+show1).val().split(',');
                        var ss = '';
                        for (var i = arry.length - 1; i >= 0; i--) {
                            if(arry[i]!=url){
                                ss = ss + arry[i] + ',';
                            }
                        }
                        $("#"+show1).val(ss.substr(0,ss.length-1));
                        $(this).closest("li").remove();
                    });
                }).fail(function(res, textStatus, error) {
                    try {
                        var body = JSON.parse(res.responseText);
                        alert('error: ' + body.message);
                    } catch(e) {
                        console.error(e);
                    }
                });
            });
        },
        //summernote文字编辑器里面上传图片
        uploadForSummerNote: function (file1,show1) {
            $.getJSON(URL+'summernote', function (data) {
                var uploadData = new FormData();
                uploadData.append("file", file1);
                uploadData.append('policy', data.policy);
                uploadData.append('authorization', data.authorization);
                $.ajax({
                    url: UPYUNURL,
                    type: 'POST',
                    data: uploadData,
                    cache: false,
                    processData: false,
                    contentType: false,
                }).done(function(data, textStatus) {
                    var body = jQuery.parseJSON(data);
                    $("#"+show1).summernote('insertImage', ONLINEURL+body.url, 'image name');
                }).fail(function(res, textStatus, error) {
                    try {
                        var body = JSON.parse(res.responseText);
                        alert('error: ' + body.message);
                    } catch(e) {
                        console.error(e);
                    }
                });
            });
        },
    };
    return upyun;
});
